package com.link.base.base.visit.service;

import com.link.base.base.visit.dao.mybatis.mapper.VisitMapper;
import com.link.base.base.visit.model.Visit;
import com.link.base.base.visitaccompany.model.VisitAccompany;
import com.link.base.base.visitaccompany.service.VisitAccompanyService;
import com.link.base.base.visitalcoholinfo.model.VisitAlcoholInfo;
import com.link.base.base.visitalcoholinfo.service.VisitAlcoholInfoService;
import com.link.base.base.visitcustinfo.model.VisitCustInfo;
import com.link.base.base.visitcustinfo.service.VisitCustInfoService;
import com.link.base.base.visitpic.model.VisitPic;
import com.link.base.base.visitpic.service.VisitPicService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.util.DateUtil;
import com.link.core.util.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 拜访
 *
 * @author 宁蓝昊
 * @date 2019/03/18 19:59
 */
@Service
public class VisitServiceImpl extends BasicServiceImpl<Visit> implements VisitService {
    /** 未执行*/
    private static final String EXECUTION_STATUS_UNEXECUTED = "Unexecuted";
    /** 已执行*/
    private static final String EXECUTION_STATUS_EXECUTED = "Executed";
    /** 申请*/
    private static final String TYPE_VISIT_APPLICATION = "VisitApplication";
    /** 记录*/
    private static final String TYPE_VISIT_RECORD = "VisitRecord";


    private static final Logger logger = LogManager.getLogger(VisitServiceImpl.class);
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private VisitAccompanyService visitAccompanyService;
    @Resource
    private VisitPicService visitPicService;
    @Resource
    private VisitAlcoholInfoService visitAlcoholInfoService;
    @Resource
    private VisitCustInfoService visitCustInfoService;

    @Resource
    private VisitMapper visitMapper;

    @Override
    public BasicMapper<Visit> getBasicMapper() {
        return visitMapper;
    }


    @Override
    public void beforInsert(Visit entity) throws Exception {
        // 默认等于：拜访类型+时间（yyyymmdd样式）
        if (StringUtils.isBlank(entity.getTitle())) {
            String title = entity.getVisitType() + DateUtil.getCurrentYear()
                    + DateUtil.getCurrentMonth() + DateUtil.getCurrentDay();
            entity.setTitle(title);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Visit upsertVisit(Visit entity) throws Exception {
        try {
            Long id = keyGenerateService.keyGenerate();
            entity.setId(id);
            // 获得子对象列表 并进行非空处理
            List<VisitAccompany> visitAccompanyList = entity.getVisitAccompanyList();
            visitAccompanyList = CollectionUtils.isEmpty(visitAccompanyList) ? new ArrayList<>(0) : visitAccompanyList;
            List<VisitPic> visitPicList = entity.getVisitPicList();
            visitPicList = CollectionUtils.isEmpty(visitPicList) ? new ArrayList<>(0) : visitPicList;
            List<VisitAlcoholInfo> visitAlcoholInfoList = entity.getVisitAlcoholInfoList();
            visitAlcoholInfoList = CollectionUtils.isEmpty(visitAlcoholInfoList) ? new ArrayList<>(0) : visitAlcoholInfoList;
            List<VisitCustInfo> visitCustInfoList = entity.getVisitCustInfoList();
            visitCustInfoList = CollectionUtils.isEmpty(visitCustInfoList) ? new ArrayList<>(0) : visitCustInfoList;

            String visitId = id + "";
            for (VisitAccompany item : visitAccompanyList) {
                item.setVisitId(visitId);
                visitAccompanyService.insert(item);
            }
            for (VisitPic item : visitPicList) {
                item.setVisitId(visitId);
                visitPicService.insert(item);
            }
            for (VisitAlcoholInfo item : visitAlcoholInfoList) {
                item.setVisitId(visitId);
                visitAlcoholInfoService.insert(item);
            }
            for (VisitCustInfo item : visitCustInfoList) {
                item.setVisitId(visitId);
                visitCustInfoService.insert(item);
            }
            // 对申请执行状态的处理
            String type = entity.getType();
            String sourceApplyId = entity.getSourceApplyId();
            if (StringUtils.equals(TYPE_VISIT_APPLICATION, type)) {
                //  当为拜访申请时，申请执行状态为未执行
                entity.setExecutionStatus(EXECUTION_STATUS_UNEXECUTED);
            } else if (StringUtils.equals(TYPE_VISIT_RECORD, type) && StringUtils.isNotBlank(sourceApplyId)) {
                //  当为拜访记录有来源申请id时，修改掉已有的拜访申请执行状态
                Visit sourceApply = queryById(Long.parseLong(sourceApplyId));
                sourceApply.setExecutionStatus(EXECUTION_STATUS_EXECUTED);
                update(sourceApply);
            }

            this.upsert(entity);
            return queryById(id);
        } catch (Exception e) {
            logger.error("VisitServiceImpl捕获异常: ", e);
            throw new BasicServiceException("保存拜访信息失败:" + e.getMessage());
        }
    }
}

